package com.pan.kang.framework;


import com.pan.kang.domain.vo.CommonVO;
import net.sf.cglib.beans.BeanGenerator;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map;


public class Transfer<P extends IDataModel> {

    public <P> CommonVO poToVo(P p) throws Exception {
        CommonVO commonVO = new CommonVO();
        BeanGenerator generator = new BeanGenerator();
        Field[] fields = p.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            Object value = field.get(p);
            CommonVO.setAttribute(commonVO, field.getName(), value);
            generator.addProperty(field.getName(), field.getType());
        }
        generator.setSuperclass(CommonVO.class);
        CommonVO proxy = (CommonVO) generator.create();
        DynamicAttributeMap valueMap = commonVO.valueMap;
        Iterator<Map.Entry<String, Object>> iterator = valueMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Object> entry = iterator.next();
            Object value = entry.getValue();
            PropertyDescriptor pd = DynamicValueObject.getPropertyDescriptor(proxy, entry.getKey());
            if (pd != null) {
                Method md = pd.getWriteMethod();
                md.invoke(proxy, value);
            }
        }
        return proxy;
    }
}
